﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using FireStarter.Base;


namespace FireStarterModeller.BO
{
    public class RecentProjects
    {
        private readonly string _fileName;
        private List<string> _projectsList;

        public RecentProjects(string fileName)
        {
            _fileName = fileName;
            LoadRecentProjects();
        }

        public List<string> ProjectsList
        {
            get { return _projectsList; }
        }

        public void Add(string fileName)
        {
            if (_projectsList.Contains(fileName))
            {
                _projectsList.Remove(fileName);
            }
            _projectsList.Insert(0, fileName);
            LimitList();
            SaveRecentProjects();
        }

        private void LimitList()
        {
            while (_projectsList.Count > 8)
            {
                _projectsList.RemoveAt(_projectsList.Count - 1);
            }
        }

        private void LoadRecentProjects()
        {
            bool mustCreateEmpty = false;
            FileStream fileStream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamReader streamReader = new StreamReader(fileStream);
            string xml = streamReader.ReadToEnd();
            streamReader.Close();
            if (xml.Length == 0)
            {
                xml = "<projects />";
                mustCreateEmpty = true;
            }
            fileStream.Close();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            _projectsList = new List<string>();
            XmlNodeList nodes = xmlDoc.DocumentElement.ChildNodes;
            foreach (XmlNode node in nodes)
            {
                _projectsList.Add(node.InnerText);
            }
            LimitList();
            if (mustCreateEmpty)
            {
                SaveRecentProjects();
            }
        }

        private void SaveRecentProjects()
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml("<projects />");

            XmlElement xmlElement = xmldoc.DocumentElement;
            foreach (string project in _projectsList)
            {
                XmlUtilities.createXmlElement(xmlElement, "project", project);
            }
            //if (File.Exists(_fileName))
            //	File.Delete(_fileName);
            FileStream fsxml = new FileStream(_fileName,
                FileMode.OpenOrCreate | FileMode.Truncate,
                FileAccess.Write, FileShare.ReadWrite);
            xmldoc.Save(fsxml);
            fsxml.Close();

        }
    }
}
